import _ from 'underscore'
import dispatcher from 'lib/dispatcher'
import {Scope} from 'lib/scopeFactory'

import TimeStore from 'lib/stores/time-store'
import {coreApi,sortMap,parseToChart} from '../apis/core-util'
import {tracelistApi,createGridOrder,parseToPartGrid} from '../apis/tracelist'


export default class MainScope extends Scope {
  constructor(){
    super();
    this.$state = {
      chart0:{
        loading:true
      },
      chart1:{
        loading:true
      },
      grid:{
        loading:true,
        getOrder:createGridOrder('timestamp',-1),
        fetch:this.fetchGrid.bind(this)
      }
    }
    this.chart0Api = coreApi({
      limit:5,
      urlName:'socket',
      classify:'ip',
      viewKey:'socket_time',
      type:'2',
      order:'2'
    },TimeStore.getValue);
    this.chart1Api = coreApi({
      limit:5,
      urlName:'socket',
      classify:'ip',
      viewKey:'socket_time',
      type:'3',
      order:'2'
    },TimeStore.getValue);
    this.gridApi = tracelistApi({
      urlName:'sockettracelist'
    },TimeStore.getValue,this.$state.grid.getOrder);
  }
  fetch(){
    this.chart0Api.fetch().then((data,params) => {
      this.$state.chart0 = {
        data:parseToChart(data,params)
      }
    },(err) => {
      this.$state.chart0 = {
        error:err
      }
    },(params) => {
      this.$state.chart0 = {
        loading:true,
        params:params
      }
      this.emit()
    }).always(() => {
      this.emit()
    })
    this.chart1Api.fetch().then((data,params) => {
      this.$state.chart1 = {
        data:parseToChart(data,params)
      }
    },(err) => {
      this.$state.chart1 = {
        error:err
      }
    },(params) => {
      this.$state.chart1 = {
        loading:true,
        params:params
      }
      this.emit()
    }).always(() => {
      this.emit()
    })
    this.fetchGrid()
  }
  fetchGrid(){
    this.gridApi.fetch().then((data,params) => {
      this.$state.grid = parseToPartGrid(data,params)
    },(err) => {
      this.$state.grid = {
        error:err
      }
    },(params) => {
      this.$state.grid = {
        loading:true,
        params:params
      }
      this.emit()
    }).always(() => {
      this.emit()
    })
  }
  $settime(payload){
    this.fetch()
  }
  $load(){
    this.fetch()
  }
}
